﻿using Coldairarrow.Business.Backstage.UserData;
using Coldairarrow.Business.Pay;
using Coldairarrow.Entity.Backstage.UserData;
using Coldairarrow.Entity.Frontstage.BS_TransferLog;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using WxPayAPI;

namespace Coldairarrow.Api.Controllers.Pay
{
    [Route("/PayTransfer/[controller]/[action]")]
    public class WeChatTransferController : BaseApiController
    {
        private IDbAccessor _DB;
        private readonly IOperator _Operator;
        public readonly IBS_UserRebateBusiness _UserRebateBusiness;
        public readonly IWebHostEnvironment _webHostEnvironment;
        public WeChatTransferController(IDbAccessor db, IOperator Operator, IBS_UserRebateBusiness UserRebateBusiness, IWebHostEnvironment hostEnvironment)
        {
            _DB = db;
            _Operator = Operator;
            _UserRebateBusiness = UserRebateBusiness;
            _webHostEnvironment = hostEnvironment;
        }


        public class AliRefundDTO { 
            /// <summary>
            /// 支付宝账户名/邮箱/绑定手机号
            /// </summary>
            [Required]
            public string AliName { set; get; }

            /// <summary>
            /// 提现金额
            /// </summary>
            [Required]
            public decimal Amount { set; get; }

            /// <summary>
            /// 用户名称
            /// </summary>
            [Required]
            public string UserName { set; get; }

            /// <summary>
            /// IP地址
            /// </summary>
            [Required]
            public string IP { set; get; }
        }


        /// <summary>
        /// 提现
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Object> WechatTransferMoney(CorpPayJson json)
        {
            #region//获取今日可提现额
            decimal txMoney = Int32.Parse((json.amount * 100).ToString("0.0"));
            //获取个人收益合计

            var sumData = _UserRebateBusiness.GetMyCanTransData();
            //获取个人收益合计
            var upMList = _DB.GetIQueryable<BS_UserICPoint>().Where(x => x.UserId.Equals(_Operator.UserId)).ToList();

            if (upMList.Count == 0)
            {
                throw new BusException("个人收益信息查询失败，提现失败！");
            }
            else if (upMList[0].Income < json.amount)
            {
                throw new BusException("提现金额大于收益金额，提现失败！");
            }
            else if (json.amount < 0.01M)
            {
                throw new BusException("提现金额必须大于0.01元！");
            }
            //txMoney = 1;
            if (sumData < json.amount)
            {
                throw new BusException("提现金额大于今日可提现金额，提现失败！");
            }


            //创建提现记录
            BS_Transfer tModel = new BS_Transfer();
            tModel.Id = IdHelper.GetId();
            tModel.CreateTime = DateTime.Now;
            tModel.Deleted = false;
            tModel.CreatorId = _Operator.UserId;
            tModel.UserId = _Operator.UserId;
            tModel.TXUserInfo = json.openid;
            tModel.Type = 1; //支付宝提现
            tModel.Amount = txMoney;
            tModel.UserName = json.re_user_name;
            tModel.IPInfo = json.IP;
            tModel.Time = DateTime.Now;

            //创建收益提现记录
            BS_UserRebate urModel = new BS_UserRebate();
            urModel.Id = IdHelper.GetId();
            urModel.Deleted = false;
            urModel.CreatorId = _Operator.UserId;
            urModel.CreateTime = DateTime.Now;
            urModel.SUserId = _Operator.UserId;
            urModel.Note =  "主动提现：-" + json.amount.ToString("0.00") + "收益";
            urModel.OrderMoney = 0.00M;
            urModel.ReturnDiscount = 0;
            urModel.Type = 2;
            urModel.ReturnMoney = -1 * json.amount;

            //减去个人收益
            upMList[0].Income -= json.amount;
            #endregion
            int txmoney = 1;
            WxPayData data = new WxPayData();
            data.SetValue("partner_trade_no", tModel.Id);//商户订单号

            data.SetValue("openid", json.openid);
            data.SetValue("check_name", json.check_name); //是否校验姓名
            if (!json.check_name.IsNullOrEmpty() && !json.check_name.Equals("NO_CHECK"))
            {
                data.SetValue("re_user_name", json.re_user_name); //用户姓名
            }
            data.SetValue("amount", txmoney); //付款金额
            data.SetValue("desc", json.Note); //备注


            WxPayData result = WxPayApi.Transfers(data,_webHostEnvironment.WebRootPath);//调用统一下单接口
            var result_code = result.GetValue("result_code");
            var return_code = result.GetValue("return_code");
            var err_code_des = result.GetValue("err_code_des");
            Serilog.Log.Information("WXTX.result_code" + result_code.ToString());
            Serilog.Log.Information("WXTX.return_code" + return_code.ToString());
            Serilog.Log.Information("WXTX.err_code_des" + err_code_des.ToString());
            if (result_code.ToString() == "SUCCESS" && return_code.ToString() == "SUCCESS")
            {
                tModel.State = 1;
                await _DB.InsertAsync(tModel);
                await _DB.InsertAsync(urModel);
                upMList[0].Income -= txMoney;
                await _DB.UpdateAsync(upMList[0]);
                return "ok";

            }
            else
            {
                Serilog.Log.Information(this.GetType().ToString(), "提现失败");
                tModel.State = -1;
                await _DB.InsertAsync(tModel);

                throw new WxPayException("UnifiedOrder response error!");
            }
        }
    }
}
